<template>
  <div class="qrcode">
    <div class="QRCode" style="display: none" ref="qrCodeUrl"></div>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
import FileSaver from "file-saver";
import JSZip from "jszip";

export default {
  data() {
    return {
      list: [],
      nameList:[],
      codeList:[],
      QRCodeURL: [],
      fileName: "二维码",
      backgroundImgUrl: require("@/assets/img/logo_blue.png"),
    };
  },
  mounted() {
    //this.createQrCode();
  },
  methods: {
    createQrCode(val, name,time) {
      //this.$refs.qrCodeUrl.innerHTML = "";
      this.list = [];
      this.fileName = name;
      val.forEach((item) => {
        this.nameList.push(item.name);
        this.codeList.push(item.code);
        let json = JSON.stringify({ kks: item.kks, code: item.code });
        new QRCode(this.$refs.qrCodeUrl, {
          text: json, // 需要转换为二维码的内容
          width: 250,
          height: 250,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.L,
        });
      });
      let timeOut =  setTimeout(() => {
        this.download(val);
        clearTimeout(timeOut)
      }, time);
    },
    download(data) {
      let promiseList = [];
      this.QRCodeURL = [];
      document.querySelectorAll(".QRCode img").forEach((each, index) => {
        // 查找div中的二维码图片
        let name = this.nameList[index];
        let code = this.codeList[index];
        let po = this.downloadQrCode(name, each.src,code);
        promiseList.push(po);
        //this.QRCodeURL.push(obj); // 保存创建的二维码图片地址
      });
      Promise.all(promiseList).then((res) => {
        this.batchQrCodeZip();
      }).catch((err) => {
        console.log(err);
      })
    },
    //打包下载
    batchQrCodeZip() {
      this.$emit("downLoadSuccess")
      const zip = new JSZip(); //新建一个压缩文件
      this.QRCodeURL.forEach((item, i) => {
        // 根据二维码图片地址下载文件, 并存成ArrayBuffer对象
        zip.file(
          `${item.name}(${item.code}).png`,
          item.url.split(",")[1],
          {
            base64: true,
          }
        ); // 逐个添加文件，需要加后缀".png"
      });
      zip.generateAsync({ type: "blob" }).then((content) => {
        // 生成二进制流
        FileSaver.saveAs(content, `${this.fileName}-二维码`); // 利用file-saver保存文件  自定义文件名
        this.$refs.qrCodeUrl.innerHTML = "";
      });
    },
    downloadQrCode(name, qrCodeUrl,code) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement("canvas");
        canvas.width = "560";
        canvas.height = "840";
        const ctx = canvas.getContext("2d");
        ctx.fillStyle = "rgb(40, 26, 113)";
        ctx.fillRect(0, 680, 560, 160);
        ctx.textAlign = "center";
        ctx.strokeStyle = "white";
        ctx.font = "normal normal 200 28px Microsoft YaHei";
        let strlength1 = ctx.measureText(name).width;
        ctx.font = "normal normal 200 32px Microsoft YaHei";
        let strlength2 = ctx.measureText(name).width;
        ctx.font = "normal normal 200 40px Microsoft YaHei";
        let strlength3 = ctx.measureText(name).width;
        if (strlength1 > 1080) {
          ctx.font = "normal normal 200 28px Microsoft YaHei";
          this.canvasTextAutoLine(name, ctx, 280, 730, 40, canvas);
        } else if (strlength2 > 1080 && strlength1 < 1080) {
          ctx.font = "normal normal 200 28px Microsoft YaHei";
          this.canvasTextAutoLine(name, ctx, 280, 750, 40, canvas);
        } else if (strlength2 > 520) {
          ctx.font = "normal normal 200 32px Microsoft YaHei";
          this.canvasTextAutoLine(name, ctx, 280, 750, 40, canvas);
        } else if (strlength3 > 520 && strlength2 < 520) {
          ctx.font = "normal normal 200 32px Microsoft YaHei";
          this.canvasTextAutoLine(name, ctx, 280, 770, 40, canvas);
        } else {
          ctx.font = "normal normal 200 40px Microsoft YaHei";
          this.canvasTextAutoLine(name, ctx, 280, 770, 40, canvas);
        }
        let imageData = ctx.getImageData(0, 0, 560, 840);
        for (let i = 0; i < imageData.data.length; i += 4) {
          // 当该像素是透明的,则设置成白色
          if (imageData.data[i + 3] == 0) {
            imageData.data[i] = 255;
            imageData.data[i + 1] = 255;
            imageData.data[i + 2] = 255;
            imageData.data[i + 3] = 255;
          }
        }
        ctx.putImageData(imageData, 0, 0);
        let p1 = new Promise((resolve, reject) => {
          let imgLog = new Image();
          imgLog.src = this.backgroundImgUrl;
          imgLog.onload = () => {
            ctx.drawImage(imgLog, 40, 20, 400, 100);
            resolve(true);
          };
        });
        let p2 = new Promise((resolve, reject) => {
          let imgCode = new Image();
          imgCode.src = qrCodeUrl;
          imgCode.onload = () => {
            ctx.drawImage(imgCode, 40, 160, 480, 480);
            resolve(true);
          };
        });
        Promise.all([p1, p2])
          .then((res) => {
            let url = canvas.toDataURL("image/jpg");
            //this.canvasUrl = url;
            this.QRCodeURL.push({
              name:name,
              url:url,
              code:code
            });
            canvas.parentNode.removeChild(canvas)
            //ctx.clearRect(0, 0, canvas.width, canvas.height);
          })
          .catch((e) => {
            reject(e);
          });
      }).catch((e) => {
        console.log(e);
      });
    },
    /*
     str:要绘制的字符串
     ctx:canvas对象
     initX:绘制字符串起始x坐标
     initY:绘制字符串起始y坐标
     lineHeight:字行高，自己定义个值即可
     */
    canvasTextAutoLine(str, ctx, initX, initY, lineHeight, c) {
      let lineWidth = 0;
      let canvasWidth = c.width - 20;
      let lastSubStrIndex = 0;
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {
          //减去initX,防止边界出现的问题
          ctx.strokeText(
            str.substring(lastSubStrIndex, i),
            initX,
            initY,
            canvasWidth
          );
          initY += lineHeight;
          lineWidth = 0;
          lastSubStrIndex = i;
        }
        if (i == str.length - 1) {
          ctx.strokeText(
            str.substring(lastSubStrIndex, i + 1),
            initX,
            initY,
            canvasWidth
          );
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.qrcode {
  display: flex;
  justify-content: center;
  align-items: center;
  .item {
    flex: 1;
    text-align: center;
    margin-top: 200px;
    position: relative;
    .code {
      position: absolute;
      left: 50%;
      transform: translate(-50%, 10%);
    }
  }
}
</style>